package com.lyq.interaction.controller;

import com.lyq.interaction.model.SessionMessage;
import com.lyq.interaction.service.SessionService;
import com.lyq.interaction.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/session")
public class SessionController {
    @Autowired
    private SessionService sessionService;

    /**
     * 获取所有的会话
     */
    @RequestMapping("/getMessageSession")
    public List<SessionMessage> getMessageSession(HttpSession session) {
        log.info("获取所有的会话");
        //获取登录用户id
        String token = (String) session.getAttribute("userToken");
        Claims claims = JWTUtil.checkToken(token);
        Integer userId = (Integer) claims.get("userId");
        return sessionService.getMessageSession(userId);
    }

    /**
     * 创建会话
     * @param friendId
     * @return 返回会话id
     */
    @RequestMapping("/createSession")
    public Object createSession(@RequestParam List<Integer> friendId, HttpSession httpsession) {
        log.info("创建会话 friend: {}", friendId);
        String token = (String) httpsession.getAttribute("userToken");
        Claims claims = JWTUtil.checkToken(token);
        Integer userId = (Integer) claims.get("userId");
        friendId.add(userId);
        Object session = sessionService.createSession(friendId);
        log.info("创建会话成功 session: {}", session);
        return session;
    }
}
